package com.sense.kukoo.common.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;


import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;


public class AppUtil {

    /**
     * <br> Description: 是否有网络
     * <br> Author:      lions
     * <br> Date:        2017/6/14 16:49
     *
     * @return boolean
     */
    public static boolean isNetWorkAvailable() {
        ConnectivityManager mgr = (ConnectivityManager) ApplicationContext.instance().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (mgr != null) {
            NetworkInfo info = mgr.getActiveNetworkInfo();
            if (info != null && info.getState() == NetworkInfo.State.CONNECTED) {
                return true;
            }
        }
        return false;
    }


    private static MediaPlayer mediaPlayer;

    /**
     * <br> Description: 播放系统铃声
     * <br> Author:      zhangweiqiang
     * <br> Date:        2017/7/26 10:00
     *
     * @param isSystemBll true：默认自带系统铃声，false：自己设置播放铃声
     * @param raw         数据源
     */
    public static void bellPlayed(Context context, boolean isSystemBll, int raw) {
        try {
            mediaPlayer = new MediaPlayer();
            if (isSystemBll) {
                Uri alert = RingtoneManager
                        .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                mediaPlayer.setDataSource(context, alert);
            } else {
                // 设定数据源，并准备播放
                AssetFileDescriptor file = context.getResources()
                        .openRawResourceFd(raw);
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
            }

            final AudioManager audioManager = (AudioManager) context
                    .getSystemService(Context.AUDIO_SERVICE);

            if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {

                mediaPlayer
                        .setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
                mediaPlayer.setLooping(false);
                mediaPlayer.prepare();
                mediaPlayer
                        .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mPlayer) {

                                if (mPlayer != null) {
                                    /* 当播放完毕一次后，重新指向流文件的开头，以准备下次播放。*/
                                    mPlayer.seekTo(0);
                                    mediaPlayer = null;
                                    mPlayer = null;
                                }
                            }
                        });
                mediaPlayer.start();
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            mediaPlayer = null;
        } catch (SecurityException e) {
            e.printStackTrace();
            mediaPlayer = null;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            mediaPlayer = null;
        } catch (IOException e) {
            e.printStackTrace();
            mediaPlayer = null;
        }
    }

    /**
     * <br> Description: 获取app版本号
     * <br> Author:      lionszhang
     * <br> Date:        2015/01/09 10:48
     *
     * @param context     上下文，推荐使用全局上下文
     * @param packageName app包名
     * @return 返回版本号
     */
    public static String getAppVersion(Context context, String packageName) {
        String version = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
            version = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 获取版本号
     *
     * @param isV true V1.0.0 false 1.0.0
     * @return 当前应用的版本号
     * String
     * @auther lion
     */
    public static String getAppVersion(boolean isV) {
        try {
            PackageManager manager = ApplicationContext.instance().getPackageManager();
            PackageInfo info = manager.getPackageInfo(ApplicationContext.instance().getPackageName(), 0);
            String version = info.versionName;
            if (isV) {
                version = String.format("%s%s", "V", version);
            }
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "can not get app version";
        }
    }

    public static String getAppVersionStr(){
        return "Version "+getAppVersion(false);
    }

    /**
     * <br> Description: 获取app versionCode
     * <br> Author:      liaoshengjian
     * <br> Date:        2018/1/5 14:30
     *
     * @param context     上下文，推荐使用全局上下文
     * @param packageName app包名
     * @return 返回版本号
     */
    public static int getAppVersionCode(Context context, String packageName) {
        int versionCode = 0;
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * <br> Description: 获取app versionCode
     * <br> Author:      liaoshengjian
     * <br> Date:        2018/1/5 14:30
     *
     * @return 返回版本号
     */
    public static int getCurrentVersionCode() {
        return getAppVersionCode(ApplicationContext.instance(), ApplicationContext.instance().getPackageName());
    }

    /**
     * <br> Description: 获取网络类型
     * <br> Author:      hehaodong
     * <br> Date:        2014/12/24 15:21
     *
     * @return 返回网络类型（wifi、移到网络）
     */
    public static String NetType() {
        try {
            ConnectivityManager cm = (ConnectivityManager) ApplicationContext.instance().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = cm.getActiveNetworkInfo();
            String typeName = info.getTypeName().toUpperCase(); // WIFI/MOBILE
            if (typeName.contains("WIFI")) {
                return typeName;
            } else {
                return info.getExtraInfo();
            }
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * <br> Description: 获取ApiKey
     * <br> Author:      zhangweiqiang
     * <br> Date:        2017/7/25 9:47
     *
     * @param metaKey 渠道
     * @return 返回apikey
     */
    public static String getMetaValue(String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (ApplicationContext.instance() == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = ApplicationContext.instance().getPackageManager().getApplicationInfo(ApplicationContext.instance().getPackageName(),
                    PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (PackageManager.NameNotFoundException e) {

        }
        return apiKey;
    }


    /**
     * <br> Description: 生产sessionID，也就是UUID
     * <br> Author:      hehaodong
     * <br> Date:        2014/12/23 17:07
     *
     * @return 返回uuid
     */
    public static String getSessionID() {
        return UUID.randomUUID().toString();
    }


    /**
     * <br> Description: 隐藏软键盘
     * <br> Author:      zhangweiqiang
     * <br> Date:        2017/7/25 9:57
     *
     * @param view 控制view
     */
    public static void hideSoftInput(View view) {
        InputMethodManager imm = (InputMethodManager) ApplicationContext.instance().getSystemService(
                Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * <br> Description: 显示软键盘
     * <br> Author:      yexiaochuan
     * <br> Date:        2017/8/28 14:36
     *
     * @param view 控制view
     */
    public static void showSoftInput(View view) {
        InputMethodManager imm = (InputMethodManager) ApplicationContext.instance().getSystemService(
                Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        }
    }

    /**
     * <br> Description: 强制隐藏当前页面的软键盘
     * <br> Author:      yexiaochuan
     * <br> Date:        2017/8/28 14:36
     */
    public static void hideSoftInputForce(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getApplicationContext().getSystemService(
                Context.INPUT_METHOD_SERVICE);
        try {
            imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    /**
     * <br> Description: 判断某一应用是否正在运行
     * <br> Author:      chenhuanwei
     * <br> Date:        2018/6/610:54
     *
     * @param context     上下文
     * @param packageName 应用的包名
     * @return true 表示正在运行，false 表示没有运行
     */

    public static boolean queryAppRunning(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> list = null;
        if (am != null) {
            list = am.getRunningAppProcesses();
        }
        if (list == null) {
            return false;
        }
        for (ActivityManager.RunningAppProcessInfo info : list) {
            if (info.importance == 100 && info.processName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isServiceRunning(String serviceName) {
        //校验服务是否还活着

        ActivityManager am = (ActivityManager) ApplicationContext.instance().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> infos = am.getRunningServices(100);
        for (ActivityManager.RunningServiceInfo info : infos) {
            String name = info.service.getClassName();
            if (serviceName.equals(name)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param activityName activity   com.sense.SplashActivity
     * @return true 在顶部 false 不在顶部
     * @Description 判断某一Activity是否在顶部
     * @Author Lionszhang
     * @Date 2022/3/27
     */

    public static boolean isTaskTop(Context mContext, String activityName) {
        String topActivityName = "";
        ActivityManager am = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = am
                .getRunningTasks(1);
        if (runningTasks != null && !runningTasks.isEmpty()) {
            ActivityManager.RunningTaskInfo taskInfo = runningTasks.get(0);
            topActivityName = taskInfo.topActivity.getClassName();
        }
        if (activityName.equals(topActivityName)) {
            return true;
        }
        return false;
    }


    /**
     * <br> Description: 获取已安装应用的 uid，-1 表示未安装此应用或程序异常
     * <br> Author:      chenhuanwei
     * <br> Date:        2018/6/7 10:55
     */
    public static int getPackageUid(Context context, String packageName) {
        try {
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(packageName, 0);
            if (applicationInfo != null) {

                return applicationInfo.uid;
            }
        } catch (Exception e) {
            return -1;
        }
        return -1;
    }

    /**
     * 判断某一 uid 的程序是否有正在运行的进程，即是否存活
     * Created by cafeting on 2017/2/4.
     *
     * @param context 上下文
     * @param uid     已安装应用的 uid
     * @return true 表示正在运行，false 表示没有运行
     */
    public static boolean isProcessRunning(Context context, int uid) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServiceInfos = null;
        if (am != null) {
            runningServiceInfos = am.getRunningServices(200);
        }
        if (runningServiceInfos != null) {
            for (ActivityManager.RunningServiceInfo appProcess : runningServiceInfos) {
                if (uid == appProcess.uid) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * <br> Description: 判读app是否运行
     * <br> Author:      chenhuanwei
     * <br> Date:        2018/6/5 17:34
     */
    public static boolean isAppRuning(Context context, String packageName) {
        int uid = getPackageUid(context, packageName);
        if (uid > 0) {
            boolean rstA = queryAppRunning(context, packageName);
            boolean rstB = isProcessRunning(context, uid);
            if (rstA || rstB) {
                return true;
            } else {
                //指定包名的程序未在运行中
                return false;
            }
        } else {
            //应用未安装
            return false;
        }
    }

    //判断某APP是否安装
    public static boolean isPlatformInstalled(Context context, String packageName) {
        ApplicationInfo info = null;
        try {
            info = context.getPackageManager().getApplicationInfo(packageName, 0);
            return info != null;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * <br> Description: 获取剪切板内容
     * <br> Author:      chenhuanwei
     * <br> Date:        2018/7/12 10:06
     */
    public String getClipboardContent(Context context) {
        String content = null;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager cm = (android.text.ClipboardManager)
                    context.getSystemService(Context.CLIPBOARD_SERVICE);
            if (cm == null || cm.getText() == null) {
                return "";
            }
            content = cm.getText().toString();
        } else {
            android.content.ClipboardManager cm = (android.content.ClipboardManager)
                    context.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clipData = null;
            if (cm != null) {
                try {
                    clipData = cm.getPrimaryClip();
                } catch (Exception e) {
                    e.printStackTrace();
                    return "";
                }

            }

            if (clipData == null || clipData.getItemCount() == 0) {
                return "";
            }
            if (clipData.getItemAt(0).getText() != null) {
                content = clipData.getItemAt(0).getText().toString();
            }

        }
        return content;
    }

    //判断应用是否处于前台
    public static boolean isAppOnForeground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (am == null) {
            return false;
        }
        String packageName = context.getPackageName();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
            if (processInfos == null) {
                return false;
            }
            for (ActivityManager.RunningAppProcessInfo processInfo : processInfos) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND || processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_TOP_SLEEPING) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equalsIgnoreCase(packageName)) {
                            return true;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName()
                    .equalsIgnoreCase(packageName)) {
                return true;
            }
        }
        return false;
    }


    /**
     * @Description 获取签名 hash值
     * @Author Lionszhang
     * @Date 2022/1/20
     */
    public static String printKeyHash(Activity context) {
        PackageInfo packageInfo;
        String key = null;
        try {
            String packageName = context.getApplicationContext().getPackageName();
            packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
            Log.e("Package Name=", context.getApplicationContext().getPackageName());
            for (Signature signature : packageInfo.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                key = new String(Base64.encode(md.digest(), 0));
                Log.e("printKeyHash", "Key Hash================================" + key);
            }
        } catch (PackageManager.NameNotFoundException e1) {
            Log.e("Name not found", e1.toString());
        } catch (NoSuchAlgorithmException e) {
            Log.e("No such an algorithm", e.toString());
        } catch (Exception e) {
            Log.e("Exception", e.toString());
        }
        return key;
    }


    public static void exitApp(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);

        // 2\. 通过ActivityManager获取任务栈
        List<ActivityManager.AppTask> appTaskList = activityManager.getAppTasks();

        // 3\. 逐个关闭Activity
        for (ActivityManager.AppTask appTask : appTaskList) {
            appTask.finishAndRemoveTask();
        }
    }
}
